import type { Context } from 'elysia';
import { eq, desc, asc, like, and, or, count, sql, gte, lte, inArray } from 'drizzle-orm';
import { db } from '../db';
import { products } from '../db/schema';
import { nanoid } from 'nanoid';
import { successResponse, paginatedResponse, errorResponse, createPaginationMeta, ApiError, asyncHandler, Logger } from '../utils/response';
import { logUserOperation, logDatabaseOperation } from '../utils/systemLogger';
import type { AuthContext } from '../middleware/auth';
import { checkReadOnlyAccess } from '../middleware/auth';
// import { PRODUCT_CATEGORY_NAMES } from '../db/seeds/basic-data'; // 已移除，使用数据库查询
import type { ProductQueryDTO, ProductCreateDTO, ProductUpdateDTO } from '../types/dto';

// 获取产品列表
export const getProducts = asyncHandler(async ({ query, set }: Context) => {
    const {
      current = '1',
      pageSize = '10',
      type,
      search,
      featured,
      status = 'active',
      sortBy = 'createdAt',
      sortOrder = 'desc',
      priceMin,
      priceMax,
      categoryId,
      tags: tagIds
    } = query as ProductQueryDTO;

    const pageNum = parseInt(current as string);
    const limitNum = parseInt(pageSize as string);
    const offset = (pageNum - 1) * limitNum;

    // 构建查询条件
    const conditions = [];
    
    if (type) {
      conditions.push(eq(products.type, type));
    }
    
    if (categoryId) {
      conditions.push(eq(products.categoryId, categoryId));
    }
    
    // 价格范围筛选已移除，因为数据库中只有priceRange字段
    // 如果需要价格筛选，需要解析priceRange字段
    
    if (search) {
      conditions.push(
        or(
          like(products.name, `%${search}%`),
          like(products.description, `%${search}%`),
          like(products.type, `%${search}%`)
        )
      );
    }
    
    // 标签筛选
    if (tagIds) {
      const tagIdArray = Array.isArray(tagIds) ? tagIds : [tagIds];
      const tagConditions = tagIdArray.map(tagId => 
        sql`JSON_CONTAINS(${products.tags}, ${JSON.stringify([tagId])})`
      );
      conditions.push(or(...tagConditions));
    }

    const whereClause = conditions.length > 0 ? and(...conditions) : undefined;

    // 排序
    let orderBy;
    switch (sortBy) {
      case 'id':
        orderBy = sortOrder === 'desc' ? desc(products.id) : asc(products.id);
        break;
      case 'title':
      case 'name':
        orderBy = sortOrder === 'desc' ? desc(products.name) : asc(products.name);
        break;
      case 'type':
        orderBy = sortOrder === 'desc' ? desc(products.type) : asc(products.type);
        break;
      case 'basePrice':
      case 'priceMin':
        orderBy = sortOrder === 'desc' ? desc(products.priceMin) : asc(products.priceMin);
        break;
      case 'priceMax':
        orderBy = sortOrder === 'desc' ? desc(products.priceMax) : asc(products.priceMax);
        break;
      case 'sort':
        orderBy = sortOrder === 'desc' ? desc(products.sort) : asc(products.sort);
        break;
      case 'updatedAt':
        orderBy = sortOrder === 'desc' ? desc(products.updatedAt) : asc(products.updatedAt);
        break;
      default:
        orderBy = sortOrder === 'desc' ? desc(products.createdAt) : asc(products.createdAt);
    }

    // 查询数据
    const [productList, [{ total }]] = await Promise.all([
      db.select()
        .from(products)
        .where(whereClause)
        .orderBy(orderBy)
        .limit(limitNum)
        .offset(offset),
      db.select({ total: count() })
        .from(products)
        .where(whereClause)
    ]);

    // 处理产品数据
    const processedProducts = productList.map(product => ({
      id: product.id,
      title: product.name,
      name: product.name,
      type: product.type,
      description: product.description,
      content: product.content,
      priceRange: product.priceRange,
      images: typeof product.images === 'string' ? JSON.parse(product.images || '[]') : product.images || [],
      features: typeof product.features === 'string' ? JSON.parse(product.features || '[]') : product.features || [],
      tags: typeof product.tags === 'string' ? JSON.parse(product.tags || '[]') : product.tags || [],
      craftTypes: typeof product.craftTypes === 'string' ? JSON.parse(product.craftTypes || '[]') : product.craftTypes || [],
      specifications: typeof product.specifications === 'string' ? JSON.parse(product.specifications || '{}') : product.specifications || {},
      categoryId: product.categoryId,

      sort: product.sort,
      createdAt: product.createdAt,
      updatedAt: product.updatedAt
    }));

    const pagination = createPaginationMeta(pageNum, limitNum, total);
    
    Logger.info('获取产品列表', {
      total,
      current: pageNum,
      pageSize: limitNum,
      filters: { status, type, featured, search, sortBy, sortOrder, priceMin, priceMax, categoryId, tags: tagIds }
    });
    
    return paginatedResponse(processedProducts, pagination, '获取产品列表成功');
});

// 获取单个产品（包含工艺和参数）
export const getProduct = asyncHandler(async ({ params, set }: Context) => {
    const { id } = params as { id: string };
    
    const productResult = await db.select()
      .from(products)
      .where(eq(products.id, id))
      .limit(1);
    
    const product = productResult[0];
    
    if (!product) {
      throw ApiError.notFound('产品不存在');
    }

    // 处理产品数据
    const processedProduct = {
      id: product.id,
      title: product.name,
      name: product.name,
      type: product.type,
      description: product.description,
      content: product.content,
      priceRange: product.priceRange,
      images: typeof product.images === 'string' ? JSON.parse(product.images || '[]') : product.images || [],
      features: typeof product.features === 'string' ? JSON.parse(product.features || '[]') : product.features || [],
      tags: typeof product.tags === 'string' ? JSON.parse(product.tags || '[]') : product.tags || [],
      craftTypes: typeof product.craftTypes === 'string' ? JSON.parse(product.craftTypes || '[]') : product.craftTypes || [],
      specifications: typeof product.specifications === 'string' ? JSON.parse(product.specifications || '{}') : product.specifications || {},
      categoryId: product.categoryId,

      sort: product.sort,
      createdAt: product.createdAt,
      updatedAt: product.updatedAt
    };

    Logger.info('获取产品详情', { productId: id, productTitle: product.name });

    return successResponse(processedProduct, '获取产品详情成功');
});

// 创建产品
export const createProduct = asyncHandler(async ({ body, set, user }: AuthContext) => {
    // 权限检查：只有管理员可以创建产品
    if (!user || user.role !== 'admin') {
      throw ApiError.forbidden('权限不足，只有管理员可以创建产品');
    }
    
    const createData = body as ProductCreateDTO;

    if (!createData.title || !createData.type || !createData.description) {
      throw ApiError.validation('产品标题、类型、描述为必填项');
    }

    // 产品类型验证已移除，现在使用categoryId

    // 准备产品数据
    const productData = {
      id: nanoid(),
      name: createData.title, // 使用title作为name
      type: createData.type,
      description: createData.description,
      content: createData.content || '',
      priceRange: createData.priceRange,
      images: JSON.stringify(createData.images || []),
      features: JSON.stringify(createData.features || []),
      tags: JSON.stringify(createData.tags || []),
      craftTypes: JSON.stringify(createData.craftTypes || []),
      specifications: JSON.stringify(createData.specifications || {}),
      categoryId: createData.categoryId,
      sort: createData.sort || 0
    };

    const [newProduct] = await db.insert(products).values(productData).returning();

    // 处理返回数据
    const processedProduct = {
      id: newProduct.id,
      title: newProduct.name,
      name: newProduct.name,
      type: newProduct.type,
      description: newProduct.description,
      content: newProduct.content,
      priceRange: newProduct.priceRange,
      images: typeof newProduct.images === 'string' ? JSON.parse(newProduct.images || '[]') : newProduct.images || [],
      features: typeof newProduct.features === 'string' ? JSON.parse(newProduct.features || '[]') : newProduct.features || [],
      tags: typeof newProduct.tags === 'string' ? JSON.parse(newProduct.tags || '[]') : newProduct.tags || [],
      craftTypes: typeof newProduct.craftTypes === 'string' ? JSON.parse(newProduct.craftTypes || '[]') : newProduct.craftTypes || [],
      specifications: typeof newProduct.specifications === 'string' ? JSON.parse(newProduct.specifications || '{}') : newProduct.specifications || {},
      categoryId: newProduct.categoryId,
      sort: newProduct.sort,
      createdAt: newProduct.createdAt,
      updatedAt: newProduct.updatedAt
    };

    // 记录系统日志
    await logDatabaseOperation(
      'product',
      'create',
      `创建产品: ${createData.title || createData.name}`,
      { productId: newProduct.id, type: createData.type, priceRange: `${createData.priceMin}-${createData.priceMax || createData.priceMin}` }
    );

    Logger.info('创建产品', { productId: newProduct.id, productTitle: createData.title || createData.name, type: createData.type, priceMin: createData.priceMin, priceMax: createData.priceMax });

    return successResponse(processedProduct, '产品创建成功');
});

// 更新产品
export const updateProduct = asyncHandler(async ({ params, body, set, user }: AuthContext) => {
    // 权限检查：只有管理员可以更新产品
    if (!user || user.role !== 'admin') {
      throw ApiError.forbidden('权限不足，只有管理员可以更新产品');
    }
    
    const { id } = params as { id: string };
    const updateData = body as ProductUpdateDTO;

    // 检查产品是否存在
    const existingProduct = await db.select()
      .from(products)
      .where(eq(products.id, id))
      .limit(1);

    if (existingProduct.length === 0) {
      throw ApiError.notFound('产品不存在');
    }

    // 产品类型验证已移除，现在使用categoryId

    // 准备更新数据
    const dbUpdateData: any = {};
    
    if (updateData.title !== undefined) dbUpdateData.name = updateData.title;
    if (updateData.name !== undefined) dbUpdateData.name = updateData.name; // 兼容旧字段名
    if (updateData.type !== undefined) dbUpdateData.type = updateData.type;
    if (updateData.description !== undefined) dbUpdateData.description = updateData.description;
    if (updateData.content !== undefined) dbUpdateData.content = updateData.content;
    if (updateData.priceRange !== undefined) dbUpdateData.priceRange = updateData.priceRange;
    if (updateData.images !== undefined) dbUpdateData.images = JSON.stringify(updateData.images);
     if (updateData.features !== undefined) dbUpdateData.features = JSON.stringify(updateData.features);
     if (updateData.tags !== undefined) dbUpdateData.tags = JSON.stringify(updateData.tags);
     if (updateData.craftTypes !== undefined) dbUpdateData.craftTypes = JSON.stringify(updateData.craftTypes);
     if (updateData.specifications !== undefined) dbUpdateData.specifications = JSON.stringify(updateData.specifications);
    if (updateData.categoryId !== undefined) dbUpdateData.categoryId = updateData.categoryId;

    if (updateData.sort !== undefined) dbUpdateData.sort = updateData.sort;

    const [updatedProduct] = await db.update(products)
      .set(dbUpdateData)
      .where(eq(products.id, id))
      .returning();

    // 处理返回数据
    const processedProduct = {
      id: updatedProduct.id,
      title: updatedProduct.name,
      name: updatedProduct.name, // 兼容旧字段名
      type: updatedProduct.type,
      description: updatedProduct.description,
      content: updatedProduct.content,
      priceRange: updatedProduct.priceRange,
      images: typeof updatedProduct.images === 'string' ? JSON.parse(updatedProduct.images || '[]') : updatedProduct.images || [],
      features: typeof updatedProduct.features === 'string' ? JSON.parse(updatedProduct.features || '[]') : updatedProduct.features || [],
      tags: typeof updatedProduct.tags === 'string' ? JSON.parse(updatedProduct.tags || '[]') : updatedProduct.tags || [],
      craftTypes: typeof updatedProduct.craftTypes === 'string' ? JSON.parse(updatedProduct.craftTypes || '[]') : updatedProduct.craftTypes || [],
      specifications: typeof updatedProduct.specifications === 'string' ? JSON.parse(updatedProduct.specifications || '{}') : updatedProduct.specifications || {},
      categoryId: updatedProduct.categoryId,
      sort: updatedProduct.sort,
      createdAt: updatedProduct.createdAt,
      updatedAt: updatedProduct.updatedAt
    };

    // 记录系统日志
    await logDatabaseOperation(
      'product',
      'update',
      `更新产品: ${existingProduct[0].name}`,
      { productId: id, updatedFields: Object.keys(dbUpdateData) }
    );

    Logger.info('更新产品', { productId: id, updatedFields: Object.keys(dbUpdateData).length });

    return successResponse(processedProduct, '产品更新成功');
});

// 删除产品
export const deleteProduct = asyncHandler(async ({ params, set, user }: AuthContext) => {
    // 权限检查：只有管理员可以删除产品
    if (!user || user.role !== 'admin') {
      throw ApiError.forbidden('权限不足，只有管理员可以删除产品');
    }
    
    const { id } = params as { id: string };

    // 检查产品是否存在
    const existingProduct = await db.select()
      .from(products)
      .where(eq(products.id, id))
      .limit(1);

    if (existingProduct.length === 0) {
      throw ApiError.notFound('产品不存在');
    }

    // 删除产品
    await db.delete(products).where(eq(products.id, id));

    // 记录系统日志
    await logDatabaseOperation(
      'product',
      'delete',
      `删除产品: ${existingProduct[0].name}`,
      { productId: id, productType: existingProduct[0].type }
    );

    Logger.info('删除产品', { productId: id, productTitle: existingProduct[0].name });

    return successResponse(null, '产品删除成功');
});

// 获取产品类型列表
export const getProductTypes = asyncHandler(async ({ set }: Context) => {
    // 从数据库查询产品分类
    const categories = await db.select()
      .from(products)
      .groupBy(products.type)
      .orderBy(asc(products.type));
    
    const productTypes = categories.map(item => item.type).filter(Boolean);
    
    Logger.info('获取产品分类列表', { categoriesCount: productTypes.length });
    
    return successResponse(productTypes, '获取产品分类成功');
});